<template>
  <BasicDrawer
    :title="getTitle"
    showFooter
    v-bind="$attrs"
    width="50%"
    @ok="handleSubmit"
    @register="registerDrawer"
  >
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :fieldNames="{ title: 'title', key: 'id' }"
          :treeData="treeData"
          checkable
          search
          title=" "
          toolbar
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { computed, ref, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicTree, TreeItem } from '@/components/Tree';
  import { doRoleAdd, getMenuList, getRoleMenuList } from '@/modules/system/api';
  import { FormSchemaAdd } from './data';
  import { useMessage } from '@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const treeData = ref<TreeItem[]>([]);
  const rowId = ref('0');
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: FormSchemaAdd,
    showActionButtonGroup: false,
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    if (unref(treeData).length === 0) {
      treeData.value = (await getMenuList()) as any as TreeItem[];
    }
    isUpdate.value = !!data?.isUpdate;
    rowId.value = data.record.id;
    if (unref(isUpdate)) {
      //获取权限菜单
      const menuArr = (await getRoleMenuList({
        adminRoleId: data.record.id,
      })) as string[];
      // console.log(menuArr);
      await setFieldsValue({
        ...data.record,
        menu: menuArr,
      });
    } else {
      rowId.value = '0';
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      // TODO custom api
      doRoleAdd({ ...values, id: rowId.value }).then((res) => {
        if (res.code > 0) {
          createMessage.warning(res.message);
          return;
        }
        createMessage.success(res.message);
        closeDrawer();
        emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
      });
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
